package com.yoomiito.app.net.http

import cn.droidlover.xdroidmvp.cache.SharedPref
import com.yoomiito.app.BuildConfig
import com.yoomiito.app.Constant
import com.yoomiito.app.base.App
import com.yoomiito.app.utils.NetworkUtils
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.HashMap
import java.util.concurrent.TimeUnit

/**
 * 网络请求
 */
class RetrofitClient private constructor() {
    private val mBaseUrl = BuildConfig.BaseUrl
    private val mConnectTimeoutMills = 10 * 1000L
    private val mReadTimeoutMills = 10 * 1000L
    private var mToken = SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, "")
    private val mRetrofitMap = HashMap<String, Retrofit>()//存储不同BaseUrl对应的Retrofit
    private val mClientMap = HashMap<String, OkHttpClient>()

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitClient() }
    }

    fun<S> service(serviceClass: Class<S>):S = initRetrofit().create(serviceClass)


    private fun initRetrofit(): Retrofit =
            mRetrofitMap[mBaseUrl] ?: mRetrofitMap[mBaseUrl].let {
                Retrofit.Builder()
                        .baseUrl(mBaseUrl)
                        .client(initOkHttpClient(mBaseUrl))
                        .addConverterFactory(GsonConverterFactory.create())
//                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
            }

    private fun initOkHttpClient(url: String): OkHttpClient =
            mClientMap[url] ?: mClientMap[url].let {
                OkHttpClient.Builder()
                        .connectTimeout(mConnectTimeoutMills, TimeUnit.MILLISECONDS)
                        .readTimeout(mReadTimeoutMills, TimeUnit.MILLISECONDS)
                        .addInterceptor {
                            it.proceed(
                                    it.request()
                                            .newBuilder()
                                            .header("Authorization", mToken)
                                            .header("Site","app_mugwort_android")
                                            .header("Platform", "")
                                            .build())
                        }
                        .addInterceptor(LogInterceptor())
                        .build()
            }
}